﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Profile;
using Aliyun.SmsSdk.Core.Dysmsapi.Model;
using Microsoft.Extensions.Options;

namespace Aliyun.SmsSdk.AspNetCore
{
    public class AliyunSmsService : IAliyunSmsService
    {
        public AliyunSmsOptions Options { get; set; }

        private readonly IAcsClient _acsClient;

        public AliyunSmsService(IOptions<AliyunSmsOptions> aliyunSmsOptions)
        {
            Options = aliyunSmsOptions.Value;
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", Options.AccessKeyId, Options.AccessKeySecret);
            DefaultProfile.AddEndpoint("cn-hangzhou", "cn-hangzhou", Options.Product, Options.Domain);
            _acsClient = new DefaultAcsClient(profile);
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="sendSmsRequest">发送短信请求参数<see cref="SendSmsRequest"/></param>
        /// <example>
        /// <code></code>
        /// </example>
        /// <returns>SendSmsResponse</returns>
        /// <remarks>SendSmsResponse see<see cref="SendSmsResponse"/></remarks>
        public SendSmsResponse SendSms(SendSmsRequest sendSmsRequest)
        {
            //请求失败这里会抛ClientException异常
            return _acsClient.GetAcsResponse(sendSmsRequest);
        }

        /// <summary>
        /// 发送短信
        /// </summary>
        /// <param name="phoneNumbers">必填:待发送手机号。支持以逗号分隔的形式进行批量调用，批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式</param>
        /// <param name="templateParam">必填:模板中的变量替换JSON串,如模板内容为"亲爱的${name},您的验证码为${code}"时,此处的值为{\"customer\":\"123\"}</param>
        /// <param name="outId">可选:提供给业务方扩展字段,最终在短信回执消息中将此值带回给调用者</param>
        /// <param name="templateCode">必填:短信模板，如果为空则取Options配置项</param>
        /// <param name="signName">必填:短信签名，如果为空则取Options配置项</param>
        /// <returns>SendSmsResponse</returns>
        /// <remarks>SendSmsResponse see<see cref="SendSmsResponse"/></remarks>
        public SendSmsResponse SendSms(string phoneNumbers, string templateParam, string outId = null, string templateCode = null, string signName = null)
        {
            SendSmsRequest sendSmsRequest = new SendSmsRequest();
            sendSmsRequest.PhoneNumbers = phoneNumbers;
            sendSmsRequest.TemplateParam = templateParam;
            if (string.IsNullOrEmpty(templateCode))
            {
                templateCode = Options.TemplateCode;
            }
            sendSmsRequest.TemplateCode = templateCode;
            if (string.IsNullOrEmpty(signName))
            {
                signName = Options.SignName;
            }
            sendSmsRequest.SignName = signName;
            sendSmsRequest.OutId = outId;
            //请求失败这里会抛ClientException异常
            return _acsClient.GetAcsResponse(sendSmsRequest);
        }
    }
}
